import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Task } from '../_model/task';
import { NewTaskDto } from '../_dtos/newTaskDto';
import { ListService } from './list.service';
import { Functions } from '../functions';


import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { UpdateTaskDto } from '../_dtos/updateTaskDto';
import { List } from '../_model/list';

@Injectable()

export class TaskService {
  constructor(
    private _http: Http,
    private _listService: ListService,
    private _funcs: Functions) { }

  getTasksByListId(listId: string): Observable<Task[]> {
    return this._http.get(`/api/task/${listId}`)
      .map(response => response.json() as Task[]);
  }

  getTodayTasks(uid: string): Observable<Task[]> {
    return this._http.get(`/api/task/${uid}/today`)
      .map(response => response.json() as Task[]);
  }

  /**
   * 查找待办事项名称中含有 key 关键字的事项列表
   *
   * @param {any} key 关键字
   * @returns {List[]} 匹配的事项列表
   * @memberof ListService
   */
  searchFromTitle(key): Task[] {
    const tasks: Task[] = [];
    this._listService.lists.forEach(item => {
      const res = item.tasks.filter(u => u.todo.includes(key));
      tasks.push(...res);
    });
    return tasks;
  }

  /**
   * 查找待办事项备注中含有 key 关键字的事项列表
   *
   * @param {any} key 关键字
   * @returns {List[]} 匹配的事项列表
   * @memberof ListService
 */
  searchFromNotes(key): Task[] {
    const tasks: Task[] = [];
    this._listService.lists.forEach(item => {
      const res = item.tasks.filter(u => u.notes && u.notes.includes(key));
      tasks.push(...res);
    });
    return tasks;
  }

  // 添加待办事项
  addNewTask(task: NewTaskDto): Observable<Task> {
    return this._http.post(
      `/api/task`,
      task,
      this._funcs.getRequestOptions()
    ).map(response => response.json() as Task);
  }

  // 更新待办事项
  updateTask(dto: UpdateTaskDto): Observable<any> {
    return this._http.put(
      '/api/task',
      dto,
      this._funcs.getRequestOptions()
    ).catch(this._funcs.handleHttpError);
  }

  // 删除截至日期
  clearDeadline(listId: string, index: number): Observable<any> {
    return this._http.delete(
      `/api/task/${listId}/${index}/deadline`,
      this._funcs.getRequestOptions()
    ).catch(this._funcs.handleHttpError);
  }

  // 移动待办事项到另一个清单（即在另一个清单新增要被移动的待办事项）
  moveToAnotherList(task: Task) {
    return this._http.post(
      `/api/task/move`,
      task,
      this._funcs.getRequestOptions()
    ).catch(this._funcs.handleHttpError);
  }

  // 删除待办事项
  deleteTask(listId: string, index: number): Observable<any> {
    return this._http.delete(
      `/api/task/${listId}/${index}`,
      this._funcs.getRequestOptions()
    )._catch(this._funcs.handleHttpError);
  }
}
